<template>
  <div class="app-container ">
    <FilterSearch class="filter-search" :value="queryParams" :config="configData">
    </FilterSearch>
    <div class="main">
      <div class="table">
        <el-table v-loading="tableData.loading" :data="tableData.rows" @selection-change="handleSelectionChange">
          <el-table-column type="selection" minWidth="55" align="center" />
          <el-table-column type="index" label="序号" minWidth="60">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="账号" minWidth="120"></el-table-column>
          <el-table-column prop="nickname" label="用户昵称" minWidth="120"></el-table-column>
          <el-table-column prop="realName" label="真实姓名" minWidth="120"></el-table-column>
          <el-table-column prop="deptName" label="部门" minWidth="120"></el-table-column>
          <el-table-column prop="postName" label="岗位" minWidth="120"></el-table-column>
          <el-table-column prop="phone" label="手机号码" minWidth="120"></el-table-column>
          <el-table-column prop="email" label="邮箱" minWidth="120"></el-table-column>
          <el-table-column prop="imageList" label="头像">
            <template #default="scope">
              <el-avatar :src="scope.row.imageList[0]"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" minWidth="80">
            <template #default="scope">
              {{ scope.row.gender == 'M' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色" minWidth="120">
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <dict-tag :options="statusOptions" :value="scope.row.status"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true" minWidth="200"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" sortable minWidth="180"></el-table-column>
          <el-table-column prop="updateTime" label="更新时间" sortable minWidth="180"></el-table-column>
          <el-table-column prop="id" label="操作" fixed="right" minWidth="160">
            <template #default="scope">
              <el-button v-hasPermi="['permission:user:edit']" @click="handleEdit(scope.row)"
                type="text">编辑</el-button>
              <el-button v-hasPermi="['permission:user:remove']" @click="handleRemove(scope.row)"
                type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <Pagination :total="tableData.total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
          @pagination="getList" />
      </div>
    </div>

    <!-- 添加或编辑用户配置对话框 -->
    <el-dialog :title="formInline.title" v-model="formInline.diaVis" width="880px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formInline.form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input v-model="formInline.form.username" clearable placeholder="请输入用户账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="formInline.form.nickname" clearable placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="realName">
              <el-input v-model="formInline.form.realName" clearable placeholder="请输入用户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门">
              <el-input v-model="formInline.form.deptName" clearable placeholder="请输入归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-input v-model="formInline.form.postName" clearable placeholder="请输入岗位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input v-model="formInline.form.phone" clearable placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="formInline.form.email" clearable placeholder="请输入用户邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色">
              <el-select v-model="formInline.form.roleIds" clearable multiple filterable placeholder="请选择角色">
                <el-option v-for="(item, index) in formList.roleOptions" :label="item.roleName" :value="item.id"
                  :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="formInline.form.gender">
                <el-radio :label="item.value" v-for="(item, index) in formList.genderOptions" :key="index">{{ item.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="formInline.form.status">
                <el-radio :label="item.value" v-for="(item, index) in statusOptions" :key="index">{{ item.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="头像" prop="images">
              <ImageUpload v-model="formInline.form.imageList" limit="1" uploadImgUrl="/file/user/uploadPic" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formInline.form.remark" rows="3" resize="none" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { userList, userAdd, userEdit, userRemove } from "@/api/permission/user";
import { roleListAll } from "@/api/permission/role";
import { statusOptions, genderOptions } from "@/constant";

const { proxy } = getCurrentInstance();
// 注入全局方法
const tableData = reactive({
  rows: [],
  total: 0,
  loading: false
})
const formRef = ref(null);
const handleChecked = ref({
  ids: [],
  multiple: true
});
const formList = reactive({
  roleOptions: [],
  genderOptions: genderOptions
});
const queryParams = ref({
  name: "",
  phone: "",
  status: "",
  createTime: [],
  pageNum: 1,
  pageSize: 10
});
const formInline = reactive({
  form: {
    id: null,
    nickname: '',
    realName: '',
    username: '',
    deptName: '',
    postName: '',
    gender: "F",
    imageList: [],
    phone: '',
    email: '',
    roleIds: null,  // 新增的角色ID
    status: 1,
    remark: ''
  },
  title: "新增",
  diaVis: false
});

const rules = computed(() => {
  let rules = {
    username: [
      { required: true, message: "请输入用户昵称", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          // 检查是否包含中文
          if (/[\u4E00-\u9FA5]/.test(value)) {
            callback(new Error('用户名不能包含中文'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    nickname: [
      { required: true, message: "请输入用户昵称", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
    ],
    realName: [
      { required: true, message: "请输入用户姓名", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
    ],
  }
  return rules;
})
const configData = computed(() => {
  let config = {
    itemConfig: [
      {
        type: "input",
        prop: "name",
        label: "用户名称",
        placeholder: "请输入"
      },
      {
        type: "input",
        prop: "phone",
        label: "手机号",
        placeholder: "请输入"
      },
      {
        type: "select",
        prop: "status",
        label: "状态",
        placeholder: "请选择",
        optList: statusOptions
      },
      {
        type: "datetimerange",
        prop: "createTime",
        label: "创建时间",
        dateFormate: "YYYY-MM-DD HH:mm:ss",
        placeholder: "请选择"
      },
    ],
    operate: [
      {
        icon: "Search",
        type: "primary",
        name: "查询",
        handleClick: getLoad,
        rule: false,
      },
      {
        icon: "RefreshRight",
        type: "info",
        name: "重置",
        handleClick: reset,
        rule: false,
      },
      {
        icon: "Plus",
        type: "success",
        name: "新增",
        handleClick: insert,
        rule: false,
        disabled: !proxy.$auth.hasPermi("permission:user:add")
      },
      {
        icon: "Delete",
        type: "danger",
        name: "删除",
        handleClick: remove,
        rule: false,
        disabled: handleChecked.value.multiple
      }
    ],
    rules: {},
  };
  return config;
});
function getList(page) {
  queryParams.value.pageNum = page.page;
  queryParams.value.pageSize = page.limit;
  getLoad();
}

function getLoad() {
  tableData.loading = true;
  userList(queryParams.value).then(res => {
    tableData.rows = res.data.rows;
    tableData.total = res.data.total;
    tableData.loading = false;
  });
};
function handleSelectionChange(selection) {
  handleChecked.value.ids = selection.map(item => item.id);
  if (handleChecked.value.ids.length > 0) {
    if (proxy.$auth.hasPermi("permission:user:remove")) {
      handleChecked.value.multiple = false;
    }
  } else {
    handleChecked.value.multiple = true;
  }
};
function insert() {
  formInline.title = "新增";
  formInline.diaVis = true;
}
function handleEdit(row) {
  formInline.form = {
    id: row.id,
    nickname: row.nickname,
    realName: row.realName,
    username: row.username,
    deptName: row.deptName,
    postName: row.postName,
    imageList: row.imageList,
    phone: row.phone,
    email: row.email,
    roleIds: row.roleIds,  // 新增的角色ID
    gender: row.gender,
    status: row.status,
    remark: row.remark
  };
  formInline.title = "编辑";
  formInline.diaVis = true;
};
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (formInline.title == "新增") {
        userAdd(formInline.form).then(res => {
          if (res.code == 200) {
            cancel();
            getLoad();
          }
        });
      } else {
        userEdit(formInline.form).then(res => {
          if (res.code == 200) {
            cancel();
            getLoad();
          }
        });
      }
    };
  })
}
function handleRemove(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.username + '"的数据项？').then(() => {
    userRemove([row.id]).then(res => {
      getLoad();
    });
  });
}
function remove() {
  proxy.$modal.confirm('是否确认删除编号为"' + handleChecked.value.ids + '"的数据项？').then(() => {
    userRemove(handleChecked.value.ids).then(res => {
      getLoad();
    });
  });
}
function cancel() {
  formRef.value.resetFields();
  formInline.form = {
    id: null,
    nickname: '',
    realName: '',
    username: '',
    deptName: '',
    postName: '',
    imageList: [],
    phone: '',
    email: '',
    roleIds: null,  // 新增的角色ID
    gender: "F",
    status: 1,
    remark: ''
  }
  formInline.title = "新增";
  formInline.diaVis = false;
}
const reset = () => {
  queryParams.value = {
    name: "",
    phone: null,
    status: null,
    createTime: [],
    pageNum: 1,
    pageSize: 10
  }
  getLoad();
}
function getOptions() {
  roleListAll().then(res => {
    formList.roleOptions = res.data;
  })
}
onMounted(() => {
  getLoad();
  getOptions();
})
</script>